package com.ljd.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.github.wxpay.sdk.WXPayUtil;
import com.ljd.entity.Order;
import com.ljd.entity.PayLog;
import com.ljd.mapper.PayLogMapper;
import com.ljd.service.OrderService;
import com.ljd.service.PayLogService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.ljd.utils.HttpClient;
import com.why.handler.GuliException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>
 * 支付日志表 服务实现类
 * </p>
 *
 * @author ljd
 * @since 2022-01-05
 */
@Service
public class PayLogServiceImpl extends ServiceImpl<PayLogMapper, PayLog> implements PayLogService {

    @Autowired
    OrderService orderService;
    //生成微信支付二维码接口
    @Override
    public Map<String, Object> createNative(String orderNo) {
        try {
            //1 根据订单号查询订单信息
            LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
            wrapper.eq(Order::getOrderNo,orderNo);
            Order order = orderService.getOne(wrapper);

            //2 使用map设置生成二维码需要参数
            Map<String,String> map = new HashMap<>();
            map.put("appid","wx74862e0dfcf69954"); // 关联的公众号appid
            map.put("mch_id","1558950191"); // 商户号
            map.put("nonce_str", WXPayUtil.generateNonceStr()); // 随机uuid(作为随机二维码)
            map.put("body",order.getCourseTitle());
            map.put("out_trade_no",orderNo); // 交易订单号
            map.put("total_fee",order.getTotalFee().multiply(new BigDecimal("100")).longValue()+"");
            map.put("spbill_create_ip", "127.0.0.1");
            map.put("notify_url", "http://guli.shop/api/order/weixinPay/weixinNotify\n"); // 重定向页面
            map.put("trade_type", "NATIVE");
            //3 发送httpclient请求，传递参数xml格式，微信支付提供的固定的地址
            HttpClient httpClient = new HttpClient("https://api.mch.weixin.qq.com/pay/unifiedorder");
            //设置xml格式的参数
            httpClient.setXmlParam(WXPayUtil.generateSignedXml(map,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb")); // 通过商户key，进行加密
            httpClient.setHttps(true); // 支持https
            // 执行post请求发送
            httpClient.post();
            //4 得到发送请求返回结果
            //返回内容，是使用xml格式返回
            String xml = httpClient.getContent();
            //把xml格式转换map集合，把map集合返回
            Map<String, String> xmlToMap = WXPayUtil.xmlToMap(xml);
            //最终返回数据 的封装
            Map<String, Object> m = new HashMap<>();
            m.put("out_trade_no",orderNo); //订单号
            m.put("course_id",order.getCourseId()); //课程id
            m.put("total_fee",order.getTotalFee()); //金额
            m.put("result_code",xmlToMap.get("result_code")); //返回二维码操作状态码;
            m.put("code_url",xmlToMap.get("code_url")); // 二维码地址
            return m;
        } catch (Exception e) {

            throw new GuliException(20001,"生成支付二维码失败");
        }

    }

    /**
     * 查询订单支付状态(通过第三方微信url)
     * @param orderNo
     * @return
     */
    @Override
    public Map<String, String> queryPayStatus(String orderNo) {
        try {
            // 封装参数
            Map<String,String> m = new HashMap<>();
            m.put("appid","wx74862e0dfcf69954");
            m.put("mch_id","1558950191");
            m.put("out_trade_no",orderNo);
            m.put("nonce_str",WXPayUtil.generateNonceStr());
            // 发送HttpClient
            HttpClient client = new HttpClient("https://api.mch.weixin.qq.com/pay/orderquery");
            client.setXmlParam(WXPayUtil.generateSignedXml(m,"T6m9iK73b0kn9g5v426MKfHQH7X8rKwb"));
            client.setHttps(true);
            client.post();

            // 得到请求返回内容
            String xml = client.getContent();
            Map<String, String> resultMap = WXPayUtil.xmlToMap(xml);
            return resultMap;
        } catch (Exception e) {
            throw new GuliException(20001,"支付订单查询失败");
        }
    }

    /**
     * 查询成功向表中添加记录
     * @param map
     */
    @Override
    public void updateOrderStatus(Map<String, String> map) {
        //从map中获取订单号
        String orderNo = map.get("out_trade_no");
        // 从订单号查询订单信息
        LambdaQueryWrapper<Order> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Order::getOrderNo,orderNo);
        Order order = orderService.getOne(wrapper);
        if(order == null){
            throw new GuliException(20001,"数据错误");
        }
        if(order.getStatus() != 0){
            return;
        }
        order.setStatus(1);
        orderService.updateById(order);
        // 向支付表中添加记录
        PayLog payLog = new PayLog();
        payLog.setOrderNo(orderNo);
        payLog.setPayTime(new Date());
        payLog.setTotalFee(order.getTotalFee());
        payLog.setTradeState(map.get("trade_state"));
        payLog.setTransactionId(map.get("transaction_id"));
        payLog.setPayType(1);
        payLog.setAttr(map.toString());
        baseMapper.insert(payLog);
    }
}
